package Thread;

//不写作泛型，直接让这个队列里面存储字符串
class MyBlockingQueue{
    private String[] data = new String[1000];
    //队列的起始位置
    private int head = 0;
    //队列的结束位置的下一个元素
    private int tail = 0;
    //队列中有效元素的个数
    private int size = 0;
    //提供核心方法，入队列和出队列


    public  void  put(String elem) throws InterruptedException {
        synchronized (this) {
            if (size == data.length) {
                this.wait();
            }
            data[tail] = elem;
            tail++;
            if (tail == data.length) {
                tail = 0;
            }
            size++;
            this.notify();//用来唤醒take的wait
        }
    }
    public String take() throws InterruptedException {
        synchronized (this) {
            if (size == 0) {
                this.wait();
            }
            String ret = data[head];
            head++;
            if (head == data.length) {
                head = 0;
            }
            size--;
            this.notify();//用来唤醒put中的wait
            return ret;
        }
    }

}
public class Demo24 {

    public static void main(String[] args) {
        // 生产者, 消费者, 分别使用一个线程表示. (也可以使用多个线程)

        MyBlockingQueue queue = new MyBlockingQueue();

        // 消费者
        Thread t1 = new Thread(() -> {
            while (true) {
                try {
                    String result = queue.take();
                    System.out.println("消费元素: " + result);

                    // 暂时先不 sleep
                    Thread.sleep(500);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        });

        // 生产者
        Thread t2 = new Thread(() -> {
            int num = 1;
            while (true) {
                try {
                    queue.put(num + "");
                    System.out.println("生产元素: " + num);
                    num++;
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        });

        t1.start();
        t2.start();
    }
}


